package com.bankcomm.ui;

import java.lang.reflect.Field;
import java.util.Vector;

import com.baidu.mapapi.MapActivity;
import com.bankcomm.BankcommApplication;
import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.util.PreferenceHelper;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.ui.LPTextField.MyLPTextField;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


public class BOCMyMapViewActivity extends MapActivity {
	public int mTheme = R.style.AppTheme_Default;
	private Dialog DellDialog;
	private String errorStr;
	private String errorType;
	private String errorCode;
	private String errorConfirm;
	private String errorRelogin;
	private Object errorCancel;
	protected ClientHello hello;
	  //增加联系人
	private Vector<String> phonesVector = null;
	private int phoneIndex = 0;
	private MyLPTextField scanTextField = null;
	private String[] arrTemp;
	private EditText phoneTextField = null;
	Class<?> clsContacts = null;
	Class<?> clsPhone = null;
	static final int PICK_CONTACT = 201;
	static final int PICK_BROWSER = 402;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            mTheme = PreferenceHelper.getTheme(this);
        } else {
            mTheme = savedInstanceState.getInt("theme");
        }
        setTheme(mTheme);
        super.onCreate(savedInstanceState);
        
        LPMid.getInstance().currentLon = 0;
        LPMid.getInstance().currentLat = 0;
        
        try{
        String flag=PackageManagerAndroid.ANDROIDDB.get("snapshot");
        if(!flag.equals("")){
		setDisSnapShot(flag);
        }
        }catch (Exception e) {
			// TODO: handle exception
		}
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mTheme != PreferenceHelper.getTheme(this)) {
            reload();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("theme", mTheme);
    }

    protected void reload() {
        Intent intent = getIntent();
        //overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        //overridePendingTransition(0, 0);
        startActivity(intent);
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	void initDelDialog(final String merLocalInfo) {
		DellDialog = new Dialog(this, R.style.popupAnimation);
		View telView = LayoutInflater.from(this).inflate(R.layout.tel_layout,
				null);
		DellDialog.setContentView(telView);
		DellDialog.setCancelable(true);
		DellDialog.setCanceledOnTouchOutside(true);

		Window mWindow = DellDialog.getWindow();
		mWindow.setWindowAnimations(R.style.popupAnimation);
		mWindow.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
		mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		final Button telButton = (Button) telView.findViewById(R.id.tel);
		telButton.setGravity(Gravity.CENTER);
		telButton.setText(merLocalInfo);
		telButton.setOnClickListener(new android.view.View.OnClickListener() {
			public void onClick(View v) {
				Intent telIntent = new Intent(Intent.ACTION_DIAL, Uri
						.parse("tel:" + merLocalInfo));
				BOCMyMapViewActivity.this.startActivity(telIntent);
				DellDialog.dismiss();
			}
		});
		Button cancelButton = (Button) telView.findViewById(R.id.cancel);
		cancelButton.getPaint().setFakeBoldText(true); // 设置粗体
		cancelButton
				.setOnClickListener(new android.view.View.OnClickListener() {
					public void onClick(View v) {
						if (DellDialog != null) {
							DellDialog.dismiss();
						}
					}
				});
		DellDialog.show();
	}
	
	/** 集中处理异常
	 * <error string="" errorcode=""/>
	 * <error type="timeout" string="错误信息" relogin="重新登录" cancel="退出"/>
	 * **/
	public void handleException(String errMsg) {
		if (null != errMsg && errMsg.indexOf("<error") != -1) {
			String error = Utils.getXMLResponseAttribute(errMsg, "string=\"", 0, Utils.MATCH);
			// 错误信息
//			errorStr = errorStr != null || !errorStr.equals("") ? "错误信息:"+error +"\n" : "";
			errorStr = "错误信息:"+error;
			// 错误类型
			errorType = Utils.getXMLResponseAttribute(errMsg, "type=\"", 0, Utils.MATCH);
			// errorContent = Utils.getXMLResponseAttribute(errMsg, "content=\"", 0, Utils.MATCH);
			errorCode =Utils.getXMLResponseAttribute(errMsg, "errorcode=\"", 0, Utils.MATCH);
			
			// 错误信息弹出后按钮文本
			errorConfirm = Utils.getXMLResponseAttribute(errMsg, " confirm=\"", 0, Utils.MATCH);
			errorRelogin = Utils.getXMLResponseAttribute(errMsg, "relogin=\"", 0, Utils.MATCH);
			errorCancel = Utils.getXMLResponseAttribute(errMsg, "cancel=\"", 0, Utils.MATCH);
            
			errorConfirm = errorConfirm != null ? errorConfirm : getString(R.string.quit);
			errorRelogin = errorRelogin != null ? errorRelogin : getString(R.string.relogin);
			errorCancel = errorCancel != null ? errorCancel : getString(R.string.cancel);
			errorCode = errorCode != null ? "错误码:"+errorCode +"\n" : "";
			if(!errorCode.equals("")){
				errorStr=errorCode+errorStr;	
			}else{
				errorStr=error;
			}
			
			if (errorType != null) {
				if (errorType.equals("timeout")) {
					showErrorDailog("timeout");
				}
			}else{
				showErrorDailog("normal");
			}
		} else if (null != errMsg && !"".equals(errMsg)) {
			
			if (errMsg.contains(".NullPoi")) {
				errorStr=Utils.getConfigStringFormAsset(Utils
						.getActivity(), "httpError");
			}else{
				errorStr = errMsg;	
			}
			showErrorDailog("normal");

		} else {
			// responseCode
		}
	}

	// 弹出错误提示框
	public void showErrorDailog(String type) {
		final Builder ad = new AlertDialog.Builder(this);
		ad.setTitle(getString(R.string.alert)).setMessage(errorStr);
		if (type.equals("normal")) {
			ad.setPositiveButton(R.string.quit,
					new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// BaseViewCopy.this.finish();
							// android.os.Process.killProcess(android.os.Process.myPid());
							// dialog.cancel();
						}
					}
			);
		} else if (type.equals("timeout")) {
			ad.setCancelable(false);
			ad.setPositiveButton(R.string.exit, new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					exitSystem();
				}
			})
			.setNegativeButton(R.string.relogin,
					new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					reConnect(BOCMyMapViewActivity.this);
					dialog.cancel();
				}
			});
		}
		
		if(null != ad){
			this.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ad.show();
				}
			});
		}
	}

	/**
	 * 重建加密通道
	 * @param baseViewCopy
	 */
	protected void reConnect(final BOCMyMapViewActivity baseViewCopy) {
		LPToastUtil.isBuildChannel = false;
		LPMid.getInstance().isTimeOut=true;
		LPMid.getInstance().waitDialog_.addFgTask(baseViewCopy, null, 0, 0, 0, new WaitDialog.Task(0) {

			String reply = null;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				if(!Utils.isConnectByNet()){
					throw new Exception("当前网络不可用，请稍后再试！");
				}
				hello = new ClientHello(BOCMyMapViewActivity.this, ConfigManager.SERVER_URI, LPMid.getInstance().midletVersion_, ConfigManager.CLIENT_HELLO,
						ConfigManager.CLIENT_KEY_EXCHANGE, ConfigManager.CLIENT_FACILITY_HELLO, Utils.CERTIFICATE, "");
				reply = ClientHello.getText();
			}

			public void onSuccess(WaitDialog dlg) {
				if (null != reply && !"".equalsIgnoreCase(reply)) {
					if(null != LPMid.getInstance().um_.data){
						LPMid.getInstance().um_.data.resetLoginInfo();
					}
					Message msg = new Message();
//					msg.obj = reply;
					hanlder.sendMessage(msg);
				}
				super.onSuccess(dlg);
			}
			public void onFailure(WaitDialog dlg) {
				handleException(getErrMsg());
				super.onFailure(dlg);
			}
		});
	}

	private Handler hanlder = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
//			LPMid.getInstance().um_.data = new DataStorage(BOCMyMapViewActivity.this, String.valueOf(msg.obj));
			BankcommApplication.getInstance().exit();
			Intent intent = new Intent();
			//是否进入推送消息页面 
//			if(LPMid.getInstance().um_.data.stepIntoPushMessage()){
//				intent.setClass(BOCMyMapViewActivity.this, BOCPushMessage.class);													
//			}else{
				intent.setClass(BOCMyMapViewActivity.this, BOCMainHome.class);				
//			}
			BOCMyMapViewActivity.this.startActivity(intent);
			//BaseViewCopy.this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
		}
	};
	
	/**
	 * 退出程序
	 */
	public void exitSystem() {
		/**
		 * 当退出时，要结束List中的所有activity add by chengli
		 * */
		BankcommApplication.getInstance().exit();
		// 停止程序开启的服务，保证程序退出后不会常驻内存
		Intent intent = new Intent();
		intent.setAction(getClass().getPackage().getName());
		stopService(intent);
		/**
		 * 一般是采用finish方法,但是在转换wifi和wap连接的时候会出现系统提示连接长时间死亡的情况.
		 */
		System.exit(0);
	}
	
	public void setDisSnapShot(String flag){
		if(flag.equals("yes")){
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
		}else{
	    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == this.PICK_CONTACT) {
				if (data == null) {
					LPToastUtil.getInstance().getToast("无返回数据",BOCMyMapViewActivity.this);
					return;
				}
				ContentResolver contentResolver = getContentResolver();
				if (contentResolver == null) {
					LPToastUtil.getInstance().getToast("ContentResolver Error",BOCMyMapViewActivity.this);
					return;
				}
				if (contentResolver != null) {
					Uri uri = data.getData();
					if (uri == null) {
						LPToastUtil.getInstance().getToast("该机型不支持读取联系人信息",BOCMyMapViewActivity.this);
						return;
					}
					if (uri != null) {
							getSelectedContactor(uri);
							showPhoneDialog(0);
						
					}
				}
			}
		}
	}
	
	//联系人所有的号码
	String phonename ;
	private void getSelectedContactor(Uri uri) {
		Cursor cursor = null; //Cursor提供一个查询DB的接口
		Cursor phones = null;
		String phoneNumber = null;

		if (uri != null) {
			ContentResolver cr = getContentResolver();
			cursor = cr.query(uri, null, null, null, null);

			if (cursor != null && cursor.moveToFirst()) {
				try {
					String fieldID = (String) getFieldValue(clsContacts, "_ID");
					String fieldname = (String)getFieldValue(clsContacts, "DISPLAY_NAME");
					Utils.printOutToConsole("fieldname---------------------------->"+fieldname);
					String id = cursor.getString(cursor
							.getColumnIndexOrThrow(fieldID));
					phonename = cursor.getString(cursor.getColumnIndexOrThrow(fieldname));
					Utils.printOutToConsole("phonename---------------------------->"+phonename);
					Class<?> clsCDK = getDeclaredSubClass(
							"android.provider.ContactsContract",
							"CommonDataKinds");
					clsPhone = getDeclaredSubClass(clsCDK.getName(), "Phone");
					Uri fieldURI = (Uri) getFieldValue(clsPhone, "CONTENT_URI");
					String fieldC_ID = (String) getFieldValue(clsPhone,
							"CONTACT_ID");
					String fieldP_NM = (String) getFieldValue(clsPhone,
							"NUMBER");

					phones = cr.query(fieldURI, null, fieldC_ID + "=" + id,
							null, null);

					if (phonesVector != null) {
						phonesVector.clear();
					} else {
						phonesVector = new Vector<String>();
					}

					while (phones.moveToNext()) {
						phoneNumber = phones.getString(phones
								.getColumnIndexOrThrow(fieldP_NM));
						phoneNumber = phoneNumber.replaceAll("\\D", "");
						if (phoneNumber.startsWith("86")) {
							phoneNumber = phoneNumber.substring(2);
						}
						phonesVector.add(phoneNumber);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (phones != null) {
						phones.close();
						phones = null;
					}

					if (cursor != null) {
						cursor.close();
						cursor = null;
					}
				}
			}
		}
	}
	
	//选中联系人后 弹出选择号码单选框
	protected void showPhoneDialog(int index) {
		try {
			if ((phonesVector == null) || (phonesVector != null && phonesVector.size() == 0)) {
				if(null != phoneTextField){
					phoneTextField.setText("");
				}
				LPToastUtil.getInstance().getToast("该联系人没有联系信息",this);
				return;
			} else if((phonesVector != null)&&(phonesVector.size() == 1)){
				if (phoneTextField != null ) {
					phoneTextField.setText(phonesVector.get(0));
				}
				if (phonesVector != null) {
					phonesVector.clear();
				}
				return;
			}else {
				String[] contents = new String[phonesVector.size()];
				for (int i = 0; i < phonesVector.size(); i++) {
					contents[i] = phonesVector.get(i);
				}
				phoneIndex = 0;
				new AlertDialog.Builder(this).setTitle((this.getResources().getString(R.string.selectPhones)))
					.setSingleChoiceItems(contents, 0,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog,
								int whichButton) {
							changePhoneIndex(whichButton);
						}
					})
					.setPositiveButton((this.getResources().getString(R.string.sure)),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 此处 用要赋值的组件的索引来完成赋值操作
							if (phoneTextField != null ) {
								phoneTextField.setText(phonesVector.get(phoneIndex));
							}
							if (phonesVector != null) {
								phonesVector.clear();
							}
						}
					}
				).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Object getFieldValue(Class<?> cls, String fieldName) {
		Object obj = null;
		if (cls != null) {
			try {
				Field field = cls.getField(fieldName);
				if (!field.isAccessible()) {
					field.setAccessible(true);
				}
				obj = field.get(fieldName);
				Utils.printOutToConsole("field value: " + field);

			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}
	
	private void changePhoneIndex(int which) {
		phoneIndex = which;
	}
	
	//找出android底层Contacts的接口
	private Class<?> getDeclaredSubClass(String superName, String subName) {
		Class<?> clsSuper;
		Class<?> clsContacts = null;
		try {
			clsSuper = Class.forName(superName);//返回与带有给定字符串名superName的类或接口相关联的 Class 对象

			Class<?>[] subClasses = clsSuper.getDeclaredClasses();//返回该类的所有成员或接口的数组
			for (Class<?> cls : subClasses) {
				if (cls.getSimpleName().equals(subName)) {
					clsContacts = cls;
					break;
				}
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clsContacts;
	}
	
	 //增加联系人zd(添加号码)
	public void setPhoneLPTextField(EditText textField) {
		phoneTextField  = textField;
	}
	
	//调出系统联系人界面
	public void getPeopleConnects(Activity bv) {
		if (phonesVector != null) {
			phonesVector.clear();
		} else {
			phonesVector = new Vector<String>();
		}
		Uri uri = null;
		
		try {
				clsContacts = getDeclaredSubClass(
						"android.provider.ContactsContract", "Contacts"); //调用底层Contacts接口
				if (clsContacts != null) {
					Field field;
					try {
						field = clsContacts.getDeclaredField("CONTENT_URI");
						String varName = field.getName();
						Utils.printOutToConsole(varName);
						uri = (Uri) field.get(varName); //取值
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchFieldException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
		} catch (Exception ex) {
			
		}
		if (null != uri) {
			Intent intent = new Intent(Intent.ACTION_PICK, uri);
			startActivityForResult(intent, PICK_CONTACT);
		}
	}
}
